package com.gb.config;

import com.gb.filter.OAuth2Filter;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro配置
 *
 * @author lgoodbook@163.com
 * @version 1.0.0
 * @Date 2017-08-10 10:27
 */
@Configuration
public class ShiroConfig {

    protected Logger log = LoggerFactory.getLogger(ShiroConfig.class);

    /**
     * Shiro 配置资源权限
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        log.info("======ShiroConfig.shiroFilter======");
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();

        // 必须设置 SecurityManager
        shiroFilter.setSecurityManager(securityManager);

        //oauth过滤
        Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
        filters.put("oauth2", new OAuth2Filter());
        shiroFilter.setFilters(filters);

        //配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/**/*.css", "anon");
        filterMap.put("/**/*.js", "anon");
        filterMap.put("/**/*.html", "anon");
        filterMap.put("/favicon.ico", "anon");
        filterMap.put("/captcha.jpg", "anon");
        filterMap.put("/","anon");
        filterMap.put("/login","anon");

        filterMap.put("/**", "authc");//表示需要认证才可以访问
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        log.info("Shiro拦截器工厂类注入成功");
        return shiroFilter;
    }

    /**
     * 配置核心安全事务管理器
     * @return SecurityManager
     */
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    /**
     * 身份认证realm; (这个需要自己写，账号密码校验；权限等)
     *
     * @return
     */
    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        return myShiroRealm;
    }
}
